<template>
	<div class="page-wrapper">
		<el-form :inline="true">
            <!-- <el-form-item>
				<el-input v-model="state.queryForm.department_name" placeholder="部门名称" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-button @click="getDataList()">查询</el-button>
			</el-form-item> -->
			<el-form-item>
				<el-button type="primary" @click="addOrUpdateHandle()" v-if="hasRule('system/org/index/add')">新增</el-button>
			</el-form-item>
		</el-form>
		<el-table :key="tableKey" v-loading="state.dataListLoading" :data="state.dataList" row-key="id" border width="100%" height="100%" :default-expand-all="isExed">
			<el-table-column prop="department_name" label="名称" header-align="center">
                <template #header>
                    <div class="w100 textC rel">
                        <div class="abs-l">
                            <el-button type="primary" @click="openandclose" size="small" :icon="Sort" style="padding: 3px 11px;height: 22px;">{{ isExed?'折叠全部':'展开全部' }}</el-button>
                        </div>
                        部门名称
                    </div>
                </template>
            </el-table-column>
			<el-table-column prop="pid" label="上级" header-align="center" align="center">
                <template #default="scope">
					<span v-if="scope.row.pid == 0"></span>
					<span v-else-if="scope.row.parent">{{scope.row.parent.department_name}}</span>
				</template>
            </el-table-column>
			<el-table-column prop="code" label="部门编号" header-align="center" align="center"></el-table-column>
			<el-table-column prop="sort" label="排序" header-align="center" align="center"></el-table-column>
			<el-table-column prop="status" label="状态" header-align="center" align="center">
                <template #default="scope">
					<span @click.stop="handleSwitchChange(scope.row)">
                        <el-switch
                            v-model="scope.row.status"
                            inline-prompt
                            :active-value="1"
                            :inactive-value="0"
                            active-text="启用"
                            inactive-text="禁用"/>
                    </span>
				</template>
            </el-table-column>
			<el-table-column label="操作" fixed="right" header-align="center" align="right" width="400">
				<template #default="scope">
					<el-button type="success" link @click="handleCheck(scope.row, 1)" v-if="hasRule('admin/customer/index/out')&&scope.row.code">查看批次库存</el-button>
					<el-button type="success" link @click="handleCheck(scope.row, 2)" v-if="hasRule('admin/customer/index/out')">查看出库记录</el-button>
					<el-button type="primary" link @click="addOrUpdateHandle(scope.row.id, true)" v-if="hasRule('system/org/index/add')">添加下级</el-button>
					<el-button type="primary" link @click="addOrUpdateHandle(scope.row.id)" v-if="hasRule('system/org/index/update')">修改</el-button>
					<el-button type="danger" link @click="deleteHandle(scope.row.id)" v-if="hasRule('system/org/index/delete')">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
        <el-dialog v-model="visible" :title="title" width="1430px" center :destroy-on-close="true">
           <div class="w100">
            <div class="flex mb10 flexL" v-loading="loadformdata">
                <div>出库时间：</div>
                <div class="mr10">
                    <el-date-picker :shortcuts="SHORTCUTS" v-model="record_time" style="width:240px;" @change="dataChange" type="daterange" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" clearable />
                </div>
                <div class="mr10">
                    <el-select :disabled="!!search.productName || !!search.productIds.length" v-model="search.expProductName" placeholder="排除产品" :filterable="canfilterable" clearable style="width: 100%;">
                        <el-option v-for="i in productList" :key="i.value" :label="i.label" :value="i.label" />
                    </el-select>
                </div>
                <div class="mr10">
                    <el-select :disabled="!!search.expProductName" v-model="search.productName" placeholder="选择产品" :filterable="canfilterable" clearable style="width: 100%;" @change="selectChange($event)">
                        <el-option v-for="i in productList" :key="i.value" :label="i.label" :value="i.label" />
                    </el-select>
                </div>
                <div class="mr10">
                    <el-select :disabled="!!search.expProductName" v-model="search.productIds" placeholder="选择属性" multiple collapse-tags collapse-tags-tooltip :filterable="canfilterable" clearable style="width: 100%;" no-data-text="请先选择产品">
                        <el-option v-for="i in attrList" :key="i.value" :label="i.label" :value="i.value" />
                    </el-select>
                </div>
                <div class="mr10">
                    <el-input v-model="search.batch_no" :placeholder="itemType==1?'按批次号(纯数字部分)搜索':'按批次号搜索'" clearable style="width: 200px;"></el-input>
                </div>
                <div>
                    <el-button type="primary" @click="searchHandle()">按产品搜索</el-button>
                </div>
            </div>
            <div class="mb10">
                表格当前页数据出入库数量汇总(不含分页)：<span class="bold">{{ totalNum }}</span><span v-if="itemType==1" class="bold ml40">已出库总数：{{ totalNum2 }}</span><span v-if="itemType==1" class="bold ml40">剩余总数：{{ totalNum3 }}</span>
            </div>
            <el-scrollbar height="600px">
                <el-table :data="itemList" border style="width: 100%" width="100%" height="100%" v-if="itemType==1">
                    <el-table-column prop="order_sn" label="入库单号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="in_time" label="入库时间" header-align="center" align="center" width="100"></el-table-column>
                    <el-table-column prop="product_name" label="入库产品" header-align="center" align="center" width="240">
                        <template #default="scope">
                            <span>{{ scope.row.product_name }}-{{ scope.row.product_attr }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="batch_no" label="批次号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="quantity" label="入库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="isused" label="已出库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="shengyu" label="剩余库存" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作人" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="created_at" label="操作时间" header-align="center" align="center" width="100"></el-table-column>
                </el-table>
                <el-table :data="itemList" border style="width: 100%" width="100%" height="100%" v-if="itemType==2">
                    <el-table-column prop="order_sn" label="出库单号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="out_time" label="出库时间" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="out_type" label="出库类型" header-align="center" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.out_type == 1">生产出库</span>
                            <span v-if="scope.row.out_type == 2">销售出库</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="product_name" label="出库产品" header-align="center" align="center">
                        <template #default="scope">
                            <span>{{ scope.row.product_name }}-{{ scope.row.product_attr }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="出库数量" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="batch_no" label="出库批次号" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作人" header-align="center" align="center"></el-table-column>
                    <el-table-column prop="created_at" label="操作时间" header-align="center" align="center"></el-table-column>
                </el-table>
            </el-scrollbar>
            <div v-if="state2.total>0">
                <el-pagination
                    :current-page="state2.page"
                    :page-sizes="state2.pageSizes"
                    :page-size="state2.per_page"
                    :total="state2.total"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="sizeChangeHandle2"
                    @current-change="currentChangeHandle2"
                >
                </el-pagination>
            </div>
           </div>
        </el-dialog>
	</div>
</template>

<script setup lang="ts">
import { useCrud } from '@/hooks'
import { reactive, ref, computed } from 'vue'
import AddOrUpdate from './add-or-update.vue'
import { IHooksOptions } from '@/hooks/interface'
import { useOrgAddApi } from '@/api/org'
import { ElMessage } from 'element-plus'
import { Sort } from '@element-plus/icons-vue'
import { hasRule } from '@/utils/tool'
import { getInventoryItem, getProductSkuList } from '@/api/api'
import { SHORTCUTS } from '@/config'
const canfilterable = ref(true)
const state: IHooksOptions = reactive({
	dataListUrl: '/api/strator/department/tree/all',
	deleteUrl: '/api/strator/department/delete',
    dataAll: true,
	isPage: false,
    page: 1,
    per_page: 9999,
})
const tableKey = ref('');
const itemType = ref(1);
const itemCode = ref('');
const isExed = ref(true);
const loadformdata = ref(false);
const openandclose = () => {
    tableKey.value = +new Date();
    isExed.value = !isExed.value;
}
const dataList = computed(() => {
    return createTreeData(state.dataList);
})
const createTreeData = (list: any[]|undefined) => {
    const treelist = [];
    list.forEach(item => {
        if (item.children?.length) {
            item.children.forEach(e => {
                e.canAdd = true;
                e.parentName = item.department_name;
            });
        }
        const additem = {
            ...item,
            children: [],
        }
        // 有子菜单的情况
		if (item.children && item.children.length > 0) {
			additem.children?.push(...createTreeData(item.children))
		}
        treelist.push(additem);
    })
    return treelist;
}
const addOrUpdateRef = ref()
const addOrUpdateHandle = (id?: Number, isOne?: any) => {
	addOrUpdateRef.value.init(id, isOne)
}
const handleSwitchChange = (row: any) => {
    useOrgAddApi({
        id: row.id,
        pid: row.pid,
        department_name: row.department_name,
        sort: row.sort,
        status: row.status,
    }).then((result) => {
        ElMessage.success('修改成功')
    }).catch((err) => {
        
    });
}

const productList = ref([])
const productAllList = ref([])
const attrList = ref([])
const totalNum = ref(0);
const totalNum2 = ref(0);
const totalNum3 = ref(0);
const state2 = reactive({
    page: 1,
    pageSizes: [1, 10, 20, 50, 100, 200, 500, 1000, 10000],
    per_page: 10,
    total: 0,
})
const search = ref({
    start: '',
    end: '',
    productIds: [],
    productName: '',
    expProductName: '',
    batch_no: '',
})
const record_time = ref([])
// 选择时间范围
const dataChange = (e: any) => {
	if(e){
		search.value.start = e[0] + ' 00:00:00'
		search.value.end = e[1] + ' 23:59:59'
	}else{
		search.value.start = ''
		search.value.end = ''
	}
}
const title = ref('');
const checkname = ref('');
const checktype = ref('');
const visible = ref(false);
const itemList = ref([]);

const sizeChangeHandle2 = (e) => {
    state2.per_page = e;
    getLog();
}
const currentChangeHandle2 = (e) => {
    state2.page = e;
    getLog();
}
const handleCheck = (row, type) => {
    itemType.value = type;
    itemCode.value = row.code;
    search.value.productIds = [];
    search.value.productName = '';
    search.value.expProductName = '';
    search.value.start = '';
    search.value.end = '';
    search.value.batch_no = '';
	record_time.value = [];
    totalNum.value = 0;
    totalNum2.value = 0;
    totalNum3.value = 0;
    checkname.value = row.department_name;
    checktype.value = type;
    if(type==1){
        title.value = row.department_name + '入库记录';
        loadformdata.value = true;
    }else{
        title.value = row.department_name + '出库记录';
    }
    getProductSkuList({page:1,per_page:9999}).then((result) => {
        productAllList.value = result.data.data.reverse();
        // 去掉重复产品
        const onleList = [];
        productAllList.value.forEach(item => {
            if (!onleList.some(i => i.label == item.name)) {
                onleList.push({
                    label: item.name,
                    value: item.id,
                })
            }
        });
        productList.value = onleList;
        if(type==1){
            loadformdata.value = false;
            search.value.productName = '心型染发夹';
            setTimeout(()=>{
                selectChange('心型染发夹');
            },100)
        }
        resolve(true);
    }).catch((err) => {
        loadformdata.value = false;
    });
    getLog();
}
const selectChange = (val) => {
    // console.log(i, val);
	if (val) {
		const list = productAllList.value.filter(i => i.name == val);
        // console.log('list', list);
		attrList.value = list.map(item => {
            let label = item.attr_name_fill+'-'+item.attr_name;
            if(!item.attr_name_fill){
                label = item.attr_name;
            }
            return {
                ...item,
                label: label,
                value: item.id,
            }
        })
		search.value.productIds = []
	} else {
		attrList.value = []
		search.value.productIds = []
	}
    // console.log(val, options.value[i]);
}
const getLog = () => {
    itemList.value = [];
    visible.value = true;
    let params = {
        department_name: checkname.value,
        page: state2.page,
        per_page: state2.per_page,
        type: checktype.value,
    };
    // 查看批次库存
    if(itemType.value == 1){
        params = {
            check_ft: 1,
            batch_no: itemCode.value,
            page: state2.page,
            per_page: state2.per_page,
        }
    }
    if(search.value.productIds.length){
        params.productIds = search.value.productIds;
        delete params.expProductName;
    }else if(search.value.productName){
        params.productName = search.value.productName;
        delete params.expProductName;
    }
    if(search.value.expProductName){
        params.expProductName = search.value.expProductName;
        delete params.productIds;
        delete params.productName;
    }
    if(search.value.start&&search.value.end){
        params.start = search.value.start;
        params.end = search.value.end;
    }
    if(search.value.batch_no){
        if(itemType.value == 1){
            params.batch_no = search.value.batch_no + '-' + itemCode.value;
        }else{
            params.batch_no = search.value.batch_no;
        }
    }
    getInventoryItem(params).then((result) => {
        if(search.value.productIds.length || search.value.productName || search.value.expProductName){
            result.data.forEach(item => {
                if(item.isused >= item.quantity){
                    item.isused = item.quantity;
                }
                item.shengyu = Math.floor(item.quantity - item.isused);
            })
            itemList.value = result.data;
            state2.total = 0;
        }else{
            result.data.data.forEach(item => {
                if(item.isused >= item.quantity){
                    item.isused = item.quantity;
                }
                item.shengyu = Math.floor(item.quantity - item.isused);
            })
            itemList.value = result.data.data;
            state2.total = result.data.total;
        }
        const ttttal = itemList.value.reduce((total,item)=>total+item.quantity, 0);
        const ttttal2 = itemList.value.reduce((total,item)=>total+item.isused, 0);
        totalNum.value = Math.ceil(ttttal);
        totalNum2.value = Math.ceil(ttttal2);
        totalNum3.value = Math.ceil(ttttal - ttttal2);
    }).catch((err) => {
        
    });
}
const searchHandle = () => {
    getLog();
}
const { getDataList, deleteHandle } = useCrud(state)
</script>
